package com.jic.market.common.util;

import com.jic.market.enums.ResourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.nio.charset.Charset;
/**
 * description: ResourceLoader
 * date: 2020/2/29 17:44
 * author: wangys
 * version: 1.0
 */
@Slf4j
public class ResourceLoader {

    /**
     * 加载下载资源目录下的资源
     */
    public static Resource loadDownloadResource(ResourceEnum resourceName) {
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                    .getResources("classpath*:" + resourceName.getPath() + resourceName.getName());
            if (resources == null || resources.length == 0) {
                return null;
            }
            return resources[0];
        } catch (IOException e) {
            log.error("load resource {} fail, msg={}", resourceName, e.getMessage());
            return null;
        }
    }

    /**
     * 加载下载资源目录下的资源
     */
    public static Resource loadDownloadResource(String resourceName) {
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                    .getResources("classpath*:" + resourceName);
            if (resources == null || resources.length == 0) {
                return null;
            }
            return resources[0];
        } catch (IOException e) {
            log.error("load resource {} fail, msg={}", resourceName, e.getMessage());
            return null;
        }
    }

    public static String loadDownloadResourceAsString(String resourceName) {
        final Resource resource = loadDownloadResource(resourceName);
        try {
            return resource == null ? null
                    : IOUtils.readFromInputStream(resource.getInputStream(), Charset.forName("UTF-8"), false);
        } catch (IOException e) {
            return null;
        }
    }

}
